package com.sy.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sy.dto.UserDTO;
import com.sy.dto.UserPageQueryDTO;
import com.sy.pojo.User;
import com.sy.result.PageResult;
import com.sy.result.Result;
import com.sy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/admin/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    @ApiOperation("查询全部分页")
    public Result<PageResult> findAll(UserPageQueryDTO userPageQueryDTO){
        //请求打印日志记录
        log.info("用户分页查询：{}",userPageQueryDTO);
        //调用业务层获取分页数据
        PageResult pageResult= userService.findAll(userPageQueryDTO);

        return Result.success(pageResult);
    }


    @GetMapping("/doExistPhone")
    @ApiOperation("查询手机号是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "要验证的手机号" ,name = "phone",
                    required = true,
                    dataTypeClass =String.class)
    })
    public Result<String> doExistPhone(String phone){
        //打印请求数据日志
        log.info("手机号为：{}",phone);
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(queryWrapper);
        if(user==null){
            return Result.success();
        }else {
            return Result.error("手机号已经存在");
        }
    }

    /**
     * 修改用户
     * @param userDTO
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("修改用户")
    public Result update(@RequestBody UserDTO userDTO){
        try {
            //打印请求数据日志
            log.info("修改用户信息：{}",userDTO);
            //调用用户业务逻辑
            User user=new User();
            BeanUtils.copyProperties(userDTO,user);
            //根据用户的id修改员工信息
            userService.updateById(user);
        } catch (Exception e) {
            throw new RuntimeException("修改用户信息失败");
        }

        return Result.success("修改用户信息成功");
    }


    @GetMapping("/doExistUsername")
    @ApiOperation("查询用户名是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "要验证的用户名",name = "username",
                    required = true,
                    dataTypeClass =String.class)
    })
    public Result<String> doExistUsername(String username){
        //打印请求数据日志
        log.info("用户名为：{}",username);
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = userService.getOne(queryWrapper);
        if(user==null){
            return Result.success();
        }else {
            return Result.error("用户名已经存在");
        }
    }

    @PostMapping("save")
    @ApiOperation("新增用户")
    public Result save(@RequestBody UserDTO userDTO){
        try {
            log.info("添加用户信息：{}",userDTO);
            //调用业务处理逻辑
            User user=new User();
            BeanUtils.copyProperties(userDTO,user);
            //设置默认密码
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            //设置创建时间
            user.setCreatetime(LocalDateTime.now());
            userService.save(user);
        } catch (BeansException e) {
            throw new RuntimeException("添加失败");
        }
        return Result.success("添加成功");
    }

    @PostMapping ("delete")
    @ApiOperation("删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户的id集合",name ="ids",required = true,
                    dataTypeClass = List.class)
    })
    public Result delete(@RequestBody List<Integer> ids){
        try {
            log.info("删除用户：{}",ids);
            //删除的user表中的数据，由于后台系统由employee表的用户登录，所以不用判断是否是当前登录用户
            //删除的员工中没有当前登录用户，可以进行逻辑删除
            //update user set is_delete=0  where in (2,4,5)
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.in(User::getUid,ids);
            User user=new User();
            user.setIsDelete(0);
            userService.update(user,queryWrapper);
        } catch (Exception e) {
            throw new RuntimeException("删除失败");
        }
        return Result.success("删除成功");

    }
}
